package com.atguigu.gmall.common.config.thread;

import com.atguigu.gmall.common.config.thread.properties.ThreadProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@Configuration
@EnableConfigurationProperties({ThreadProperties.class})
public class AppThreadAutoConfiguration {

    @Bean
    public ThreadPoolExecutor getThreadPoolExecutor(ThreadProperties threadProperties){

        return new ThreadPoolExecutor(
                threadProperties.getCorePoolSize(), //核心线程数
                threadProperties.getMaximumPoolSize(),//最大线程数
                threadProperties.getKeepAliveTime(), //弹性线程存活时间
                TimeUnit.MINUTES,//时间单位
                new LinkedBlockingQueue<>(threadProperties.getWorkQueueSize()), //阻塞队列
                new ThreadFactory() {
                    int i = 1;
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        thread.setName("线程池：核心线程"+ i++);
                        thread.setPriority(10);
                        return thread;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy());
    }
}
